<?php


namespace App\Http\Controllers\Admin;
use App\Http\Controllers\BaseController;
use App\Models\UserReadLog;
use Illuminate\Http\Request;

class UserReadLogController extends BaseController
{
    /**
     * 列表
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request) {
        $user_id = $request->input('user_id');
        if (!$user_id)
            $this->failed('缺少user_id参数');

        $log = new UserReadLog(['user_id' => $user_id]);
        $list = $log->withCertain('article', ['title'])->where('user_id', $user_id)->orderBy("id", "desc")
            ->paginate(per_page());
        return $this->paginate($list);
    }

    public function tag(Request $request) {
        $user_id = $request->input('user_id');
        if (!$user_id)
            $this->failed('缺少user_id参数');

        $log = new UserReadLog(['user_id' => $user_id]);
        $table = $log->getTable();
        $list = $log->selectRaw('article_tags.id,max(title) as title, count(*) as total')->from($table . " as log")->where('user_id', $user_id)->join('article_tag_relates', function ($join) {
            $join->on('log.article_id', 'article_tag_relates.article_id');
        })->join('article_tags', function ($join) {
            $join->on('article_tags.id', 'article_tag_relates.article_tag_id');
        })->groupBy('article_tags.id')->orderBy('total', 'desc')->paginate(per_page());
        return $this->paginate($list);
    }

}

